package cn.ac.cintcm.webapp.controller;

import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import cn.ac.cintcm.model.FeedBack;
import cn.ac.cintcm.model.Therapy;
import cn.ac.cintcm.service.FeedbackManager;
import cn.ac.cintcm.service.TherapyManager;

public class FeedBackFormController extends BaseFormController {
	private FeedbackManager fm;
	private TherapyManager tm;
	
	private transient final Log log = LogFactory.getLog(FeedBackFormController.class);
	
	public void setFeedBackManager(FeedbackManager fm) {
		this.fm = fm;
	}
	
	public void setTherapyManager(TherapyManager tm) {
		this.tm = tm;
	}
	
	public FeedBackFormController() {
		this.setCommandClass(FeedBack.class);
		this.setCommandName("feedBack");
	}
	
	protected Object formBackingObject(HttpServletRequest request) {
		String id = request.getParameter("id");
		FeedBack fb = null;
		String tid = request.getParameter("therapy.id");
		log.debug("entering feedbackformcontroller id:" + id + " therapyid:" + tid);
		if(!StringUtils.isBlank(tid)) {
			Therapy therapy = new Therapy();
			therapy.setId(new Long(tid));
			fb = new FeedBack();
			fb.setTherapy(therapy);
			
		} else if (!StringUtils.isBlank(id)) {
			fb = fm.get(new Long(id));
		}
		return fb;
	}
	
	public ModelAndView onSubmit(HttpServletRequest request, 
			HttpServletResponse response, Object command, BindException e) {
		FeedBack feedBack = (FeedBack) command;
		String isDelete = request.getParameter("delete");
		boolean isNew = (feedBack.getId() == null) ? true : false;
        String  success = "redirect:mainMenu.html";
        Locale locale = request.getLocale();
		if (isDelete != null) {
			fm.remove(feedBack.getId());
			saveMessage(request, getText("feedBack.deleted", feedBack.getContent(), locale));
		} else {

			Therapy therapy = feedBack.getTherapy();
			therapy = tm.get(therapy.getId());
			feedBack.setFdate(new Date());
			feedBack.setDoctor(therapy.getDoctor());
			feedBack.setPatient(therapy.getPatient());
			boolean author = false;
			if (request.getRemoteUser().equals(therapy.getDoctor().getUsername())) {
				author = true;
			}
			feedBack.setAuthor(author);
			fm.save(feedBack);
            String key = (isNew) ? "feedBack.added" : "feedBack.updated";
            saveMessage(request, getText(key, feedBack.getContent(), locale));
		}
		return new ModelAndView(success);
	}
}
